<template>
  <div class="login-container">
    <el-form
      ref="loginData"
      :model="loginData"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">后台管理系统</h3>
      </div>

      <div>
        <el-radio-group
          v-model="loginData.type"
          class="type-box"
          @change="changeType"
        >
          <template v-for="t in loginTypes">
            <el-radio-button :key="t.type" :label="t.type">{{
              t.name
            }}</el-radio-button>
          </template>
        </el-radio-group>
      </div>

      <template v-if="loginData.type == 'UsernamePassword'">
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginData.username"
            placeholder="账号"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginData.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </template>
      <template v-else-if="loginData.type == 'PhoneCode'">
        <el-form-item prop="username">
          <span class="svg-container">
            <span class="iconfont icon-hntshoujihao" />
          </span>
          <el-input
            ref="username"
            v-model="loginData.username"
            placeholder="手机号"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item v-if="loginData.type == 'PhoneCode'" prop="phone-code">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginData.code"
            placeholder="验证码"
            name="code"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="get-phone-code" @click="getPhoneCode">
            <el-button
              :loading="codeLoading"
              type="primary"
            >获取验证码</el-button>
          </span>
        </el-form-item>
      </template>
      <template v-else-if="loginData.type == 'PhonePassword'">
        <el-form-item prop="username">
          <span class="svg-container">
            <i class="el-icon-mobile-phone" />
          </span>
          <el-input
            ref="username"
            v-model="loginData.username"
            placeholder="手机号"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginData.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </template>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
      >登陆</el-button>

      <!-- <div class="tips">
        <span style="margin-right:20px;">username: admin</span>
        <span> password: any</span>
      </div> -->
    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { Message } from 'element-ui'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (this.loginData.type === 'PhoneCode') {
        validatePhone(rule, value, callback)
      } else if (!validUsername(value)) {
        callback(new Error('账号必须4~20个字符'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value.match(/^1[3-9]\d{9}$/)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length > 100) {
        callback(new Error('密码必须6~100个字符'))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (!value.match(/^\d{4}$/)) {
        callback(new Error('密码必须4个数字'))
      } else {
        callback()
      }
    }
    return {
      loginTypes: [
        { type: 'UsernamePassword', name: '账号密码登录' },
        { type: 'PhoneCode', name: '手机验证码登录' },
        { type: 'PhonePassword', name: '手机密码登录' }
      ],
      loginData: {
        username: 'admin',
        password: '123456',
        type: 'UsernamePassword',
        // 手机验证码
        code: '',
        // 验证码编号
        id: ''
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        code: [{ required: true, trigger: 'blur', validator: validateCode }]
      },
      loading: false,
      codeLoading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    changeType() {
      this.loginData.password = ''
      this.loginData.username = ''
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    getPhoneCode() {
      this.$refs.loginData.validate((valid) => {
        if (valid) {
          this.codeLoading = true
          this.$store
            .dispatch('user/loginPhoneCode', this.loginData.username)
            .then((res) => {
              this.loginData.id = res.data
              this.codeLoading = false
              Message({
                message: '验证码获取成功',
                type: 'success',
                duration: 3 * 1000
              })
            })
            .catch(() => {
              this.codeLoading = false
            })
        } else {
          console.log('获取验证码出错')
          return false
        }
      })
    },
    handleLogin() {
      this.$refs.loginData.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('user/login', this.loginData)
            .then(() => {
              this.$router.push({ path: this.redirect || '/' })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      // 解决  输入框自动填充背景色无法去除的问题，让动画很久才生效
      &:-webkit-autofill,
      &:-webkit-autofill:hover,
      &:-webkit-autofill:focus,
      &:-webkit-autofill:active {
        -webkit-transition-delay: 99999s;
        -webkit-transition: color 99999s ease-out,
          background-color 99999s ease-out;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.5);
    background: rgba(255, 255, 255, 0.3);
    border-radius: 5px;
    color: #454545;
  }

  .type-box {
    width: 100%;
    text-align: center;
    margin-bottom: 20px;
    .type-groups {
      text-align: center;
    }
  }
}
</style>

<style lang="scss" scoped>
$dark_gray: #e3e7e9;
$light_gray: rgb(255, 255, 255);

.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  background: url("../../assets/login-bg.jpg") no-repeat center;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .get-phone-code {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
